poj3984-迷宫问题
迷宫问题
Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 36567 Accepted: 20632 Description
定义一个二维数组:
int maze[5][5] = { 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, };
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input
0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1 0
Sample Output
(0, 0) (1, 0) (2, 0) (2, 1) (2, 2) (2, 3) (2, 4) (3, 4) (4, 4)
dfs~开两个数组或者栈或者队列记录下路径就好(队列比较方便~)
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <map>
#include <list>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
#include <iostream>
#define go(i,a,b) for(int i=a;i<=b;i++)
#define og(i,a,b) for(int i=a;i>=b;i--)
using namespace std;
int maze[10][10];
int vis[10][10] = {0};
int dxy[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
int f = 0;
queue<int> c1,c2;
void dfs(int x,int y)
{
if(x == 4 && y == 4)//找到了
{
c1.push(x);
c2.push(y);
f = 1;//这里一定要弄个flag,不然return到上一层的话是没有break的
return;
}
else if(x > 4 || y > 4 || x < 0 || y < 0)//超出边界了
return;
if(maze[x][y] == 0 && !vis[x][y])
{
c1.push(x);
c2.push(y);
vis[x][y] = 1;//已经访问过了
go(i,0,4)
{
x += dxy[i][0];
y += dxy[i][1];
dfs(x,y);
if(f) break;
}
}
}
int main()
{
f = 0;
go(i,0,4)
{
go(j,0,4)
{
scanf("%d",&maze[i][j]);
}
}
dfs(0,0);
while(!c1.empty())
{
printf("(%d,%d)\n",c1.front(),c2.front());
c1.pop();
c2.pop();
}
return 0;
}